<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useLoading } from '@sa/hooks';
import { fetchCreateSmsConfig, fetchUpdateSmsConfig } from '@/service/api/business/sms-config';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'SmsConfigOperateDrawer'
});

interface Props {
  operateType: NaiveUI.TableOperateType;
  rowData?: Api.Business.SmsConfig | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const { loading: submitLoading, startLoading: startSubmitLoading, endLoading: endSubmitLoading } = useLoading();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增短信配置',
    edit: '编辑短信配置'
  };
  return titles[props.operateType];
});

type Model = Api.Business.SmsConfigOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    supplier: '',
    accessKeyId: '',
    accessKeySecret: '',
    signature: '',
    sdkAppId: '',
    templateId: '',
    status: 0,
    username: '',
    password: ''
  };
}

type RuleKey = Extract<
  keyof Model,
  'supplier' | 'accessKeyId' | 'accessKeySecret' | 'signature' | 'sdkAppId' | 'templateId' | 'status'
>;

const rules: Record<RuleKey, App.Global.FormRule | App.Global.FormRule[]> = {
  supplier: createRequiredRule('短信厂商不能为空'),
  accessKeyId: createRequiredRule('AccessKeyId不能为空'),
  accessKeySecret: createRequiredRule('AccessKeySecret不能为空'),
  signature: createRequiredRule('签名不能为空'),
  sdkAppId: createRequiredRule('SdkAppId不能为空'),
  templateId: createRequiredRule('模板ID不能为空'),
  status: createRequiredRule('启用状态不能为空')
};

const supplierOptions = [
  { label: '阿里云短信', value: 'aliyun' },
  { label: '腾讯云短信', value: 'tencent' },
  { label: '华为云短信', value: 'huawei' },
  { label: '云片短信', value: 'yunpian' },
  { label: '容联云短信', value: 'ronglian' },
  { label: '极光短信', value: 'jiguang' },
  { label: '其他', value: 'other' }
];

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
    model.username = '';
    model.password = '';
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  startSubmitLoading();

  try {
    if (props.operateType === 'add') {
      const { error } = await fetchCreateSmsConfig(model);
      if (error) return;
    }

    if (props.operateType === 'edit') {
      const { error } = await fetchUpdateSmsConfig(model);
      if (error) return;
    }

    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    endSubmitLoading();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="600" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NDivider>基础配置</NDivider>

        <NFormItem label="短信厂商" path="supplier">
          <NSelect
            v-model:value="model.supplier"
            :options="supplierOptions"
            placeholder="请选择短信厂商"
          />
        </NFormItem>

        <NFormItem label="AccessKeyId" path="accessKeyId">
          <NInput v-model:value="model.accessKeyId" placeholder="请输入AccessKeyId" />
        </NFormItem>

        <NFormItem label="AccessKeySecret" path="accessKeySecret">
          <NInput
            v-model:value="model.accessKeySecret"
            type="password"
            show-password-on="click"
            placeholder="请输入AccessKeySecret"
          />
        </NFormItem>

        <NFormItem label="短信签名" path="signature">
          <NInput v-model:value="model.signature" placeholder="请输入短信签名" />
        </NFormItem>

        <NFormItem label="SdkAppId" path="sdkAppId">
          <NInput v-model:value="model.sdkAppId" placeholder="请输入SdkAppId" />
        </NFormItem>

        <NFormItem label="模板ID" path="templateId">
          <NInput v-model:value="model.templateId" placeholder="请输入短信模板ID" />
        </NFormItem>

        <NDivider>状态设置</NDivider>
        <NFormItem label="启用状态" path="status">
          <DictRadio v-model:value="model.status" dict-code="sys_normal_disable" />
        </NFormItem>
        
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped>
.flex-center {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
